/**
* wechat mp webtoken
*/
import randomStr from 'random-string';
import qr from 'qr-image';
import config from 'config';
import _debug from 'debug';
import client from './redis';

const debug = _debug('app:lib:wx_mplogin:');

/**
* save userinfo to session
* redirect
*/
export function* afterScanCode() {
  debug('_wechat_userinfo: ', this._wechat_userinfo);

  let uuid = this.query.state;

  this.session._wechat_userinfo = this._wechat_userinfo;

  yield client.set(config.userinfo_prefix + uuid, JSON.stringify(this.session._wechat_userinfo));

  this.io.emit(`${uuid}`, {url: `${config.domain}/oauth/success/${uuid}`});

  debug('session: ', this.session);

  this.redirect(this.query.redirect_uri || '/404');
}

/**
* answer login status question from web browser.
*/
export function* status() {
  debug('prefix: ', config.userinfo_prefix + this.params.uuid);

  let _wechat_userinfo = yield client.get(config.userinfo_prefix + this.params.uuid);

  if (!this.query.redirect_uri) {
    return this.body = {
      status: 404,
      message: `未填写重定向地址`
    }
  }

  if (!_wechat_userinfo) {
    return this.body = {
      status: 404,
      message: '未登录'
    }
  }

  this.session._wechat_userinfo = JSON.parse(_wechat_userinfo);

  debug('session: ', this.session);
  this.redirect(this.query.redirect_uri || '/404');
}

/**
* fetch qrcode, uuid and websocket listen domain.
*/
export function* genQrcode() {
  let uuid = randomStr();
  let uri = config.domain + '/oauth/signin_mp/' + uuid;
  debug('url: ', uri);
  var svg_string = qr.imageSync(uri, { type: 'svg' });
  this.body = {
    svg: svg_string,
    uuid: uuid,
    domain: config.domain
  }
}
